package me.cloud.common.transmitter;

import cn.hutool.json.JSONUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import me.boot.common.constant.Const;
import me.boot.common.context.ContextUtil;
import me.boot.common.data.model.UserInfo;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @Description:
 * @author: Sylar
 * @date: 2021年09月28日 4:19 下午
 */
@Slf4j
public class TransmitUserInfoFeighClientIntercepter implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //从应用上下文中取出user信息，放入Feign的请求头中
        UserInfo user = ContextUtil.getUser();
        if (user != null) {
            try {
                String userJson = JSONUtil.toJsonStr(user);
                requestTemplate.header(Const.KEY_USERINFO_IN_HTTP_HEADER, URLDecoder.decode(userJson, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                log.error("用户信息设置错误", e);
            }
        }
    }
}
